import { isNgTemplate } from "@angular/compiler";
import { Component, OnInit, Output, EventEmitter, Input } from "@angular/core";
import { ToastService } from 'ng-devui';
import { DrawerService, IDrawerOpenResult } from 'ng-devui/drawer';
import { OrderComponent } from '../../home/order/order.component';
import { DialogService } from "ng-devui/modal";
import { OrderManageService } from "src/app/@core/order-manage.service";
import { AuthGuardService } from '../../@core/auth-guard-service.guard';
import { OrderParams } from '../../@core/interface/manage'
import { Router } from "@angular/router";
@Component({
  selector: "app-order-list",
  templateUrl: "./order-list.component.html",
  styleUrls: ["./order-list.component.scss"],
})

export class OrderListComponent implements OnInit {
  @Input() searchContent: string
  @Input() orderStatusFlag: string

  options = [
    {
      name: '近一周订单',
      value: 1
    },
    {
      name: '近三个月订单',
      value: 2
    },
    {
      name: '近半年订单',
      value: 3
    }]

  orderStateRoot = {
    'SUCCESS': '已完成',
    'NOTPAY': '待付款',
    'CLOSED': '已关闭',
    'REVOKED': '已取消',
    'USERPAYING': '正在支付中',
    'PAYERROR': '支付失败'
  }

  orderState = {
    'SUCCESS': '已完成',
    'NOTPAY': '待付款',
    'CLOSED': '已取消',
    'REVOKED': '已取消',
    'USERPAYING': '待付款',
    'PAYERROR': '待付款'
  }

  stateCode = {
    'orders': -1,
    'unfinished': 1,
    'canceled': 2,
    'finished': 3
  }

  orderRange = { value: -1 }
  basicDataSource = null;
  total = 3;
  ceshitime = new Date(new Date().setMonth(new Date().getMonth() + 2)).getTime();
  drawer: IDrawerOpenResult;
  rotateDegrees = 0;
  userId = parseInt(localStorage.getItem('userId'))
  type: boolean

  queryParams = {
    timeRange: null,
    userId: parseInt(localStorage.getItem('userId')),
    page: 1,
    pageSize: 10,
    orderStatusFlag: null,
    collectionName: null,
    issuer: null,
  }

  constructor(private toastService: ToastService,
    private drawerService: DrawerService,
    private dialogService: DialogService,
    private orderManageService: OrderManageService,
    private authGuardService: AuthGuardService,
    private router: Router) { }

  ngOnInit(): void {
    this.type = localStorage.getItem("ROLE") == 'admin'
  }

  copyId(id: string) {
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(id).then(() => {
        this.toastService.open({ value: [{ severity: 'success', summary: '', content: '复制成功' }] });
      }, () => {
      });
    } else {
      let textArea = document.createElement("textarea");
      textArea.value = id;
      textArea.style.position = "absolute";
      textArea.style.opacity = '0';
      textArea.style.left = "-999999px";
      textArea.style.top = "-999999px";
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      new Promise((res, rej) => {
        document.execCommand('copy') ? this.toastService.open({ value: [{ severity: 'success', summary: '', content: '复制成功' }] }) : rej;
        textArea.remove();
      });
    }
  }

  knowMore(collectionIndex, orderData) {
    var subCollectionIndex = orderData.subCollectionIndex
    this.openDrawer(collectionIndex, orderData, subCollectionIndex)
  }

  timeTransform(time) {
    var date = new Date(time)
    var Y = date.getFullYear() + '-'
    var M =
      (date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1) + "-";
    var D =
      (date.getDate() < 10
        ? "0" + (date.getDate())
        : date.getDate()) + " ";

    var h = date.getHours() > 9 ? date.getHours() : "0" + date.getHours();
    var m = date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes();
    var s = date.getSeconds() > 9 ? date.getSeconds() : "0" + date.getSeconds();
    return Y + M + D + h + ":" + m + ":" + s;
  }

  getList(stateParam: string, searchName: string) {
    this.queryParams.collectionName = searchName
    this.queryParams.orderStatusFlag = this.stateCode[stateParam]
    this.orderStatusFlag = stateParam
    if (this.orderRange === null) {
      this.orderRange = { value: -1 }
    }
    this.queryParams.timeRange = this.orderRange.value
    this.orderManageService.getOrderList(this.queryParams).subscribe((res) => {
      if (res.code == 0) {
        this.basicDataSource = res.data.order
        if (res.data.order) {
          this.basicDataSource.forEach((item) => {
            item.orderStatus = this.orderState[item.orderStatus]
            item.createdTime = this.timeTransform(item.createdTime)
            item.paymentTime = this.timeTransform(item.paymentTime)
            item.price = parseFloat(item.price).toFixed(2)
          })
        }
        this.total = res.data.totalNum
      }
      else {
        this.authGuardService.showModalPanel('fail', res.msg)
      }
    })
  }

  pageSizeChange(pageSize) {
    this.queryParams.pageSize = pageSize
    this.pageIndexChange(1)
  }

  pageIndexChange(pageIndex) {
    this.queryParams.page = pageIndex
    this.getList(this.orderStatusFlag, this.searchContent)
  }

  cancelOrder(orderId) {
    this.openDialog(orderId, 'warning', '取消订单', '请确认是否取消该订单？')
  }

  payOrder(collectionIndex, orderData) {
    var subCollectionIndex = orderData.subCollectionIndex
    this.openDrawer(collectionIndex, orderData, subCollectionIndex)
  }

  openDialog(orderId: number, dialogtype?: string, title?: string, content?: string) {
    const results = this.dialogService.open({
      id: 'dialog-service',
      width: '300px',
      maxHeight: '600px',
      title: title,
      backdropCloseable: true,
      dialogtype: dialogtype,
      content: content,
      buttons: [
        {
          cssClass: 'primary',
          text: '确认',
          handler: ($event: Event) => {
            this.orderManageService.cancelOrder(orderId, this.userId).subscribe((res) => {
              if (res.code == 0) {
                this.authGuardService.showModalPanel('success', res.msg)
                this.getList(this.orderStatusFlag, this.searchContent)
              }
              else {
                this.authGuardService.showModalPanel('fail', res.msg)
              }
            })
            results.modalInstance.hide()
          }
        },
        {
          cssClass: 'primary',
          text: '关闭',
          handler: ($event: Event) => {
            results.modalInstance.hide()
          }
        }
      ],
    })
  }

  openDrawer(collectionIndex: string, orderData, subCollectionIndex?) {
    this.drawer = this.drawerService.open({
      drawerContentComponent: OrderComponent,
      width: '31.25%',
      zIndex: 1000,
      isCover: true,
      fullScreen: true,
      backdropCloseable: false,
      escKeyCloseable: false,
      position: 'right',
      bodyScrollable: true,
      data: {
        collectionIndex,
        orderData,
        subCollectionIndex,
        close: (event) => {
          this.drawer.drawerInstance.hide();
          this.getList(this.orderStatusFlag, this.searchContent)
        }
      }
    });
  }

  onToggle(event) {
    this.rotateDegrees = event ? 180 : 0;
  }
}
